﻿using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace CIS.Web.Controllers
{
	[RoutePrefix("SysConferenceModel")]
	public class SysConferenceModelController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.SysConferenceModelMaster.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status));
			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.ModelName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				ModelName = x.ModelName,
				ModelDetail = x.ModelDetail,
				ModelPic = x.ModelPic,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				CreateDate = LoginUser.Language == ConstValues.Language.Cn ? x.CreateDate.Value.ToString("yyyy-MM-dd") : x.CreateDate.Value.ToString("MM/dd/yyyy"),
				CreateIP = x.CreateIP,
				Creator = x.Creator
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.SysConferenceModelMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					modelName = data.ModelName,
					modelNameEn = data.ModelNameEn,
					modelPic = Path.GetFileName(data.ModelPic),
					sort = data.Sort,
					status = data.Status,
					remark = data.Remark,
					modelDetail = data.ModelDetail,
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
					JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Modify(SysConferenceModelModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var exist = await DbContext.SysConferenceModelMaster
					.FirstOrDefaultAsync(x => x.ModelName == model.ModelName && x.ID != model.Id);
			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
					string.Format(Resources.MsgRecordExist, Resources.ModelName)),
					JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.SysConferenceModelMaster.FirstOrDefaultAsync(x => x.ID == model.Id);
			if (result != null)
			{
				if (model.ModelPic != null)
				{
					if (model.ModelPic.ContentLength > ConstValues.PicMaxLength)
					{
						string errorMessage = Resources.MsgPicOverflowError;
						return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
							JsonRequestBehavior.AllowGet);
					}
					string folder = ConstValues.SysConferenceModelImg;
					string fileName = ConstValues.TableId.SysConferenceModelMaster + ConstValues.strHyphen +
							DateTime.Now.ToString("yyyyMMdd") + ConstValues.strHyphen +
							Utility.GetRandom() + Path.GetExtension(model.ModelPic.FileName); ;
					model.ModelPicPath = Path.Combine(folder, fileName);

					var saveFileTask = Task.Run(() =>
					{
						string pfolder = Server.MapPath(ConstValues.SysConferenceModelImg);
						string pFullPath = Path.Combine(pfolder, fileName);
						if (!Directory.Exists(pfolder))
						{
							Directory.CreateDirectory(pfolder);
						}
						if (model.ModelPic != null)
						{
							model.ModelPic.SaveAs(pFullPath);
						}
					});
					Task.WaitAll(saveFileTask);
				}
				result.ModelName = model.ModelName?.Trim();
				result.ModelNameEn = model.ModelNameEn?.Trim();
				result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
				result.Remark = model.Remark?.Trim();
				result.Status = model.Status;
				if (model.ModelPic != null)
				{
					result.ModelPic = model.ModelPicPath;
				}
				result.ModelDetail = model.ModelDetail;
				result.Updater = LoginUser.UserName;
				result.UpdateDate = DateTime.Now;
				result.UpdateIP = LoginUser.IP;

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		public async Task<ActionResult> ConferenceModelImg(string id)
		{
			var img = await DbContext.SysConferenceModelMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (img != null)
			{
				return File(img.ModelPic, Application.Octet, Path.GetFileName(img.ModelPic));
			}
			else
			{
				return File("~/Images/ConferenceNoPic.png", Application.Octet, Path.GetFileName("~/Images/ConferenceNoPic.png"));
			}
		}
	}
}